package com.hnchances.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hnchances.domain.dto.UserRegisterDTO;
import com.hnchances.domain.entity.Student;
import com.hnchances.domain.entity.User;
import com.hnchances.domain.response.CodeEnum;
import com.hnchances.domain.response.ResponseResult;
import com.hnchances.domain.util.JwtProperties;
import com.hnchances.domain.util.JwtUtil;
import com.hnchances.domain.vo.LoginVO;
import com.hnchances.mapper.StudentMapper;
import com.hnchances.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisClientConfig;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private CaptchaController controller;
    @Autowired
    private JwtProperties jwtProperties;


    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ResponseResult register(@RequestBody UserRegisterDTO userRegisterDTO) {
//        给手机发送验证码(使用工具类自动生成验证码暂时无需使用阿里云)
//        controller.generateCaptcha();
        //获取验证码信息,判断验证码是否正确
        JedisClientConfig config = DefaultJedisClientConfig.builder().password("123456").build();
        Jedis jedis = new Jedis("192.168.100.168", 6379, config);
        String captcha = jedis.get("captcha");
        if (captcha == null || !captcha.equals(userRegisterDTO.getCaptcha())) {
            return ResponseResult.error(CodeEnum.SYSTEM_VERIFY_CODE_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegisterDTO, user);
        //判断是学生注册
        if (userRegisterDTO.getStatus() == 0) {
            //根据身份证关联学生成员表的表字段学生ID，如班级无此人，不予以注册
            Student student = studentMapper.selectByIdCard(userRegisterDTO.getIdCard());
            if (student == null) {
                return ResponseResult.error(CodeEnum.NO_THIS_ONE);
            }
            //填充学生特有用户表字段
            user.setStudentID(student.getId().intValue());
            user.setClassID(student.getClassID());
            //更新学生表中的生日信息
            studentMapper.update(Wrappers.<Student>update().eq("idcard", userRegisterDTO.getIdCard()).set("birthday", userRegisterDTO.getBirthday()));
        } else if (userRegisterDTO.getStatus() != 1) {
            //TODO:领导或管理注册
        }
        //填充公共字段
        user.setUserName(userRegisterDTO.getPhone());
        user.setPassWord("123456");//默认密码
        user.setCreatDateTime(LocalDateTime.now());
        user.setUpdateDateTime(LocalDateTime.now());
        user.setLastLoginDateTime(LocalDateTime.now());
        user.setUpdateByID(user.getId());
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        user.setLoginIP(request.getRemoteAddr());
        user.setStatus(0);
        user.setVerify(0);
        userMapper.insert(user);
        //注册完返回重新登陆，不用发令牌
        return ResponseResult.ok();
    }

    @PutMapping("/update")
    @ApiOperation("用户修改")
    private ResponseResult update(@RequestBody User user) {
//        if (user.getStatus()==0){
//            return ResponseResult.error(CodeEnum.NO_PERMISSION);
//        }
        userMapper.update(Wrappers.<User>update().eq("id", user.getId()).set("password", user.getPassWord()).set("phone", user.getPhone()).set("userName", user.getUserName()).set("trueName", user.getTrueName()));
        return ResponseResult.ok();
    }

    @DeleteMapping("/del")
    @ApiOperation("用户删除")
    private ResponseResult delete(@RequestBody User user) {
        if (user.getStatus() == 0) {
            return ResponseResult.error(CodeEnum.NO_PERMISSION);
        }
        userMapper.deleteById(user);
        return ResponseResult.ok();
    }

    @PostMapping("/login")
    @ApiOperation(value = "登录")
    public ResponseResult login(String username, String password) {
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, username));
        if (!user.getPassWord().equals(password)) {
            log.info("密码错误");
            return ResponseResult.error(CodeEnum.SYSTEM_PASSWORD_ERROR);
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        LoginVO loginVO = LoginVO.builder()
                .id(user.getId())
                .username(user.getPhone())
                .token(token)
                .build();
        return ResponseResult.ok(loginVO);
    }

    @GetMapping("/userinfo")
    @ApiOperation("用户信息查询")
    private ResponseResult find(Integer id) {
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getId, id));
        user.setPassWord(null);
        return ResponseResult.ok(user);
    }
}
